package net.lab1024.sa.admin.module.device.control;

import lombok.extern.slf4j.Slf4j;
import net.lab1024.sa.admin.module.device.terminal.DeviceTerminalService;
import net.lab1024.sa.admin.module.device.terminal.domain.DeviceTerminalEntity;
import net.lab1024.sa.admin.module.shell.ShellService;
import net.lab1024.sa.base.common.enumeration.DeviceRequestStatusEnum;
import net.lab1024.sa.base.common.enumeration.ExecuteStatusEnum;
import net.lab1024.sa.base.common.enumeration.ShellTypeEnum;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

/**
 * 设备执行命令
 */
@Slf4j
@Service
public class DeviceExecuteCommandService {

    private final ShellService shellService;

    private final DeviceTerminalService deviceTerminalService;

    public DeviceExecuteCommandService(ShellService shellService,
                                       DeviceTerminalService deviceTerminalService) {
        this.shellService = shellService;
        this.deviceTerminalService = deviceTerminalService;
    }

    /**
     * 部署
     */
    @Async
    public void deploy(String serialno, Integer upstream, String osType) {
        // 得到部署脚本命令
        String deployCommand = shellService.getDeployCommandByUpstreamAndOsType(upstream, osType);
        // 请求设备执行命令
        String deploy = ShellTypeEnum.DEPLOY.getStrValue();
        String msg = deviceTerminalService.executeCommand(serialno, deploy, deployCommand);
        // 获取设备终端信息
        DeviceTerminalEntity entity = deviceTerminalService.getBySerialno(serialno);
        // 判断请求状态
        boolean requestStatus = msg == null;
        // 得到请求状态枚举
        DeviceRequestStatusEnum requestStatusEnum =
                requestStatus ? DeviceRequestStatusEnum.SUCCESS : DeviceRequestStatusEnum.FAIL;
        // 设置请求状态
        entity.setRequestStatus(requestStatusEnum.getValue());
        entity.setRequestFailDesc(msg);
        // 请求成功
        if (requestStatus) {
            // 设置上游标识
            entity.setUpstreamCode(upstream);
            // 执行状态设置为执行中
            entity.setExecuteStatus(ExecuteStatusEnum.EXECUTING.getValue());
        }
        // 更新信息
        deviceTerminalService.update(entity);
    }
}
